export default class Socket {
    constructor(url) {
        this.func = null;
        this.socket = null;
        this.handler = null;
        this.locked = false;
        this.url = url;

        // 关闭页面时关闭Socket
        window.onbeforeunload = function() {
            if (this.socket !== null) {
                this.socket.close();
            }
        }

        // 这里有一个监视器,判断最后一次获取数据的时间与当前时间做比较
        // 如果超过两分钟，则关闭socket,重新链接
    }

    events(self) {
        self.socket.onopen = () => {
            console.log("Socket连接成功 => ", this.url);
            self.locked = true;
            if (self.handler !== null) {
                clearInterval(self.handler);
                self.handler = null;
            }
        };

        self.socket.onmessage = (event) => {
            // 这里记录以下时间
            self.func(event.data);
        };

        self.socket.onclose = () => {
            if (self.locked) {
                console.log("Socket连接关闭 => ", this.url);
                // self.locked = false;
                // self.handler = null;
                // self.socket = null;
                // self.reconnect();
            }
        };

        self.socket.onerror = () => {
            if (self.locked) {
                console.log("Socket连接异常 => ", this.url);
                self.locked = false;
                self.handler = null;
                self.socket = null;
                self.reconnect();
            }
        };
    }

    create(func){
        const self = this;
        self.func = func;
        self.socket = new WebSocket(self.url);
        self.events(self);
    }

    reconnect() {
        const self = this;
        if (self.locked) return;

        // 没链接上会一直连接,设置延迟,避免过多请求
        self.handler = setInterval(function() {
            console.log("Socket尝试恢复...");
            try {
                self.socket = new WebSocket(self.url);
            } catch (err) {
                return;
            }
            self.events(self);
        }, 20000);
    }

    send(data) {
        this.socket.send(JSON.stringify(data));
    }

    close() {
        console.log('Socket手动关闭.');
        this.socket.close();
    }
}